package concurrencyPractice.chapter06;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author xinya
 * @version 1.0
 * @project javacore
 * @description 6-15 使用 CompletionService 使页面元素在下载完成后立即显现出来
 * @date 2024/1/3 17:31:43
 */
public class Renderer {
    private final ExecutorService executor;

    Renderer(ExecutorService executor){
        this.executor = executor;
    }

    void renderPage(CharSequence source) throws Exception {
         List<FutureRenderer.ImageInfo> info = scanForImageInfo(source);
        CompletionService<FutureRenderer.ImageData> completionService = new ExecutorCompletionService<>(executor);
        for (final FutureRenderer.ImageInfo imageInfo: info) {
            completionService.submit(new Callable<FutureRenderer.ImageData>() {
                @Override
                public FutureRenderer.ImageData call() throws Exception {
                    return imageInfo.downloadImage();
                }
            });
        }
        renderText(source);

        try {
            for (int t = 0, n = info.size(); t <n; t ++) {
                Future<FutureRenderer.ImageData> f= completionService.take();
                FutureRenderer.ImageData imageData = f.get();
                renderImage(imageData);
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } catch (ExecutionException e) {
            throw launderThrowable(e.getCause());
        }

    }

    public static RuntimeException launderThrowable(Throwable t) {
        if (t instanceof RuntimeException) {
            return (RuntimeException) t;
        } else if (t instanceof Error) {
            throw (Error) t;
        } else
            throw new IllegalStateException("not checked", t);
    }

    List<FutureRenderer.ImageInfo> scanForImageInfo (CharSequence charSequence) {
        return null;
    }
    void renderText(CharSequence charSequence) {
        
    }
    void  renderImage(FutureRenderer.ImageData imageData) {
        
    }

    final class ImageInfo {
        FutureRenderer.ImageData downloadImage() {
            return null;
        }
    }
}
